#!/usr/bin/env python
# coding=UTF-8
import os
import logging
import logging.handlers
from optparse import OptionParser
import json
import time
import thread
import threading
import socket
# import dao

def consumer(uid, pwd):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect(('47.93.90.95', 8098))
        data = json.dumps({"t":"login", "d":{"bid":"szjt", "uid":"%s" % uid, "pwd":"%s" % pwd}})
        sock.send(data + "^lckj^")
        sock.recv(1024)
        while True:
            sock.send('{"t":"hb","d":{"res":"ok","code":"0"}}^lckj^')
            sock.recv(1024)
            time.sleep(0.001)
        
    except:
        logging.error("error=================", exc_info=True)

def main():
    db = db = dao.Game_DB();
    sql = "SELECT * FROM t_user WHERE uid>100031";
    tmpres = db.query(sql)
    for user in tmpres:
        tmpuid = user['uid']
        tmppwd = user['md5pwd']
        print tmpuid
        print tmppwd
        threading.Thread(target=consumer, args=(tmpuid, tmppwd)).start()
  

class MJ():
    def get_joker_cnt(self, card, joker):
        joker_cnt = 0
        for j in joker:
            k = card.count(j)
            joker_cnt += k
        return joker_cnt
    
    def get_jiang(self, card, joker=[]):
        r = []
        joker_cnt = 0
        for j in joker:
            k = card.count(j)
            joker_cnt += k
            for i in range(k):
                card.remove(j)
        for k in set(card):
            if joker_cnt > 0:
                r.append(k)
            else:
                if card.count(k) >= 2:
                    r.append(k)
        return r

    def get_n(self, card, jiang='', joker=[]):
        n = 0
        print "===当将牌为%s时,各种排列组合为==" % jiang
        res = []
        left_res = []
        card.sort()
        joker_cnt = 0
        all_joker = []
        for j in joker:
            k = card.count(j)
            joker_cnt += k
            for i in range(k):
                all_joker.append(j)
                card.remove(j)
        if joker_cnt >= 4:
            return 4
        joker = all_joker
        if jiang:
            jiang_cnt = card.count(jiang)
            card.remove(jiang)  
            if jiang_cnt < 2:
                joker_cnt -= 1
                joker.pop()
            else:
                card.remove(jiang)
        while card:
            c = card.pop(0)
            card_num = card.count(c) 
            if card_num >= 2:
                n += 1
                card.remove(c)
                card.remove(c)
                res.append([c, c, c])
            elif c > 40:
                if card_num + joker_cnt >= 2:
                    tmp_res = [c, ]
                    need_joker = 2 - card_num
                    n += 1
                    joker_cnt -= need_joker
                    for i in range(card_num):
                        card.remove(c)
                        tmp_res.append(c)
                    for i in range(need_joker):
                        jk = joker.pop()
                        tmp_res.append(jk)
                    res.append(tmp_res)
                else:
                    # break
                    left_res.append(c)
            elif card_num == 1:
                
                c2 = c + 1
                c3 = c + 2
                c4 = c + 3
                c2_cnt = card.count(c2)
                c3_cnt = card.count(c3)
                if c2_cnt == 2 and c3_cnt == 2:
                    n += 2
                    card.remove(c)
                    for i in range(2):
                        res.append([c, c2, c3])
                        card.remove(c2)
                        card.remove(c3)
                elif joker_cnt >= 2:
                    n += 1
                    joker_cnt -= 1
                    jk = joker.pop()
                    card.remove(c)
                    res.append([c, c, jk])
                elif c2 in card and c3 in card:
                    n += 1
                    card.remove(c2)
                    card.remove(c3)
                    res.append([c, c2, c3])
                elif joker_cnt == 1:
                    if c2 in card and c4 not in card:
                        n += 1
                        card.remove(c2)
                        joker_cnt -= 1
                        jk = joker.pop()
                        res.append([c, c2, jk])
                    elif c3 in card and c4 not in card:
                        n += 1
                        card.remove(c3)
                        joker_cnt -= 1
                        jk = joker.pop()
                        res.append([c, jk, c3])
                    else:
                        n += 1
                        joker_cnt -= 1
                        jk = joker.pop()
                        card.remove(c)
                        res.append([c, c, jk])
                else:
                    # break
                    left_res.append(c)
            else:
                c2 = c + 1
                c2_cnt = card.count(c2)
                if c2_cnt > 1:
                    c2_cnt = 1
                c3 = c + 2
                c3_cnt = card.count(c3)
                if c3_cnt > 1:
                    c3_cnt = 1
                if c2_cnt + c3_cnt + joker_cnt >= 2:
                    n += 1
                    tmp_res = [c, ]
                    need_joker = 2 - (c2_cnt + c3_cnt)
                    joker_cnt -= need_joker
                    for i in range(c2_cnt):
                        card.remove(c2)
                        tmp_res.append(c2)
                    for i in range(c3_cnt):
                        card.remove(c3)
                        tmp_res.append(c3)
                    for i in range(need_joker):
                        jk = joker.pop()
                        tmp_res.append(jk)
                    res.append(tmp_res)
                else:
                    # break
                    left_res.append(c)
                
        if joker_cnt % 3 == 0:
            n += (joker_cnt / 3)
        win_card = []
        if len(left_res) == 1:
            if joker:
                c1 = left_res[0]
                if c1 < 40:
                    if str(c1)[-1] == '9':
                        win_card = [c1 - 2, c1 - 1, c1]
                    elif str(c1)[-1] == '8':
                        win_card = [c1 - 2, c1 - 1, c1, c1 + 1]
                    elif str(c1)[-1] == '2':
                        win_card = [c1 - 1, c1, c1 + 1, c1 + 2]
                    elif str(c1)[-1] == '1':
                        win_card = [c1, c1 + 1, c1 + 2]
                    else:
                        win_card = [c1, c1 - 1, c1 - 2, c1 + 1, c1 + 2]
                else:
                    win_card = left_res
            else:
                win_card = left_res
        elif len(left_res) == 2:
            left_res.sort()
            c1 = left_res[0]
            c2 = left_res[1]
            if c2 - c1 == 0:
                win_card = [c1]
            elif c2 - c1 == 1:
                if c2 < 40:
                    if str(c2)[-1] == '9':
                        win_card = [c1 - 1]
                    elif str(c1)[-1] == '1':
                        win_card = [c2 + 1]
                    else:
                        if [c1 - 3, c1 - 2, c1 - 1] in res:
                            win_card = [c1 - 4, c1 - 1, c2 + 1]
                        else: 
                            win_card = [c1 - 1, c2 + 1]
            elif c2 - c1 == 2:
                win_card = [c1 + 1]
        print 'jjjjjj',jiang, n, res, left_res, win_card

        return n, res, left_res, win_card

    def get_win_card(self, card_str, joker_list=[], left_n=4):
        allcard = []
        for x in card_str:
            allcard.append(int(x))
        ccc = []
        for x in card_str:
            ccc.append(int(x))
        joker = []
        for x in joker_list:
            joker.append(int(x))
            
        jiang_list = self.get_jiang(allcard, joker)
        res = []
        if jiang_list:
            for jiang in sorted(jiang_list):
                ddd = sorted(ccc)
                n, rs, left_res, win_card = self.get_n(ddd, jiang, joker)
                n += 1
                if n == left_n:
                    res.extend(win_card)
        else:
            n, rs, left_res, win_card = mj.get_n(ddd, '', joker)
            if n == left_n:
                res.extend(win_card)
        return sorted([str(x) for x in set(res)])
    
    def get_seven_pairs(self, all_card, joker):
        jiang_list = []
        joker_cnt = 0
        card = []
        for x in all_card:
            card.append(x)
        for j in joker:
            k = card.count(j)
            joker_cnt += k
            for i in range(k):
                card.remove(j)
        for k in set(card):
            if card.count(k) >= 2:
                jiang_list.append(k)
                for i in range(2):
                    card.remove(k)
        if not jiang_list:
            return 0, []
        return len(jiang_list) + joker_cnt, card
    
    def check_seven_pairs(self, all_card, joker_list=[]):
        '''七对胡'''
        pair_num, win_card = self.get_seven_pairs(all_card, joker_list)
        return pair_num == 7
    
    def check_win_card(self, player, joker=[]):
        n = 0
        n += len(player.dark_bar)
        n += len(player.white_bar)
        n += len(player.pair)
        current_card = player.current_card.members
        res = []
        if n == 0 and self.room['seven_pair_win'] == 'y':
            pair_num, win_card = self.get_seven_pairs(current_card, joker)
            if pair_num >= 6:
                res.extend(win_card)
            # elif self.check_thirteen_orphans(current_card):
            #    return True
        win_card = self.get_win_card(current_card, joker, 4 - n)
        if win_card:
            logging.debug(u"用户胡牌可能:%s" % str(win_card))
            res.extend(win_card)
            res = list(set(res))
        return res
    
    def trans_card(self, card):
        res = []
        card.sort()
        for c in card:
            res.append(int(c)/10)
        return res
    
    def is_pair(self, card_list):
        if len(card_list) == 2:
            if card_list[0] == card_list[1]:
                return True
        return False
    
    def is_seq_pair(self, card_list):
        res = []
        card_list.sort()
        if len(card_list) >= 4 and len(card_list) % 2 == 0:
            for c in set(card_list):
                if card_list.count(c) != 2:
                    return False
                res.append(c)
            start_i = res[0]
            end_i = res[-1]
            if res == range(start_i, end_i+1):
                return True
        return False
    
    def is_bomb(self, card_list):
        if len(card_list) == 4:
            c = card_list[0]
            if card_list == [c] * 4:
                return True
        return False
    
if __name__ == "__main__":
    card = ['21', '21', '22', '22']
    mj = MJ()
    card_list = mj.trans_card(card)
    print mj.is_bomb(card_list)
    